﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Bifrost;
using CLIENT_EMR.BASE_COMMON;
using TextEditor;
using System.Xml;
using CLIENT_EMR.Doctor_Bll;

namespace CLIENT_EMR.TEMPLATE
{
    public partial class frmGetTemplate : DevComponents.DotNetBar.Metro.MetroForm
    {
        private string kindtid = "0";   //文书类型     
        private string section_id = "";  //所属科室
        private DataTable dataTable;
        private DataRow newrow;    
        private DataSet TextData;        //文书类型集合

        public EventHandler TemplateSelect;

        private string Kindtid;
        frmText uctext = new frmText();

        /// <summary>
        /// 当前选中的模板
        /// </summary>
        private string loadContent;        
       

        /// <summary>
        /// 
        /// </summary>       
        private string TemplateId;
       

        /// <summary>
        /// 模板类型
        /// </summary>
        private string Temptype;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="kindtid">文书类型</param>
        public frmGetTemplate(string kindtid)
        {
            InitializeComponent();
            Kindtid = kindtid;            
            uctext.Dock = DockStyle.Fill;
            groupBox3.Controls.Add(uctext);
        }

        /// <summary>
        /// 刷新操作
        /// </summary>
        /// <param name="tid"></param>
        public void Reflesh(string tid)
        {
            try
            {
                Kindtid = tid;               
                BigCheck();                                    
            }
            catch
            { }
        }

        //初始化一级目录（所属系统）
        private void InitSystemList(ref ComboBox cbobox)
        {           
            DataSet dsSys = App.GetDataSet("select * from t_data_code where type='16'");
            //初始化所属系统疾病
            dataTable = dsSys.Tables[0];
            newrow = dataTable.NewRow();
            newrow[1] = "请选择...";
            dataTable.Rows.InsertAt(newrow, 0);
            cbobox.DataSource = dataTable.DefaultView;
            cbobox.ValueMember = "ID";
            cbobox.DisplayMember = "Name";          
        }

        //初始化二级目录（病种类）
        private void InitSickList(ref ComboBox cbobox, string msg)
        {
            try
            {              
                string sql = "select s.ID,SICK_CODE," +
                            @"SICK_NAME,SICK_SYSTEM, " +
                            @"t.name as Name  from T_SICK_TYPE s " +
                            @"inner join t_data_code t on t.id=s.sick_system where t.id='" + msg + "'";
                //初始化病种
                DataSet dsSick = App.GetDataSet(sql);
                dataTable = dsSick.Tables[0];
                newrow = dataTable.NewRow();
                newrow[2] = "请选择...";
                dataTable.Rows.InsertAt(newrow, 0);
                cbobox.DataSource = dataTable.DefaultView;
                cbobox.ValueMember = "ID";
                cbobox.DisplayMember = "SICK_NAME";                
            }
            catch
            { }
        }

        private void cboBigSys_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitSickList(ref cboBigSicknessKind, cboBigSys.SelectedValue.ToString());
        }
 

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

            if (advTreeBigTemplate.SelectedNode.Parent != null)
            {
                if (cboBigUseRange.Text == "科室" || cboBigUseRange.Text == "个人")
                {
                    contextMenuStrip1.Enabled = true;
                }
                else
                {
                    contextMenuStrip1.Enabled = false;
                }
            }
            else
            {
                contextMenuStrip1.Enabled = false;
            }
                
           
        }

        /// <summary>
        /// 大模板查询函数
        /// </summary>
        private void BigCheck()
        {
            try
            {
                string Styleflag = "";
                string msg = "";
                string template_level = this.cboBigUseRange.Text.Trim();
                string sick_kind = "";
                string sys = "";
                string template_name = "";
                if (cboBigSys.SelectedIndex == 0)
                {
                    sys = this.cboBigSys.Text;
                }
                else
                {
                    sys = this.cboBigSys.SelectedValue.ToString();
                }
                if (cboBigSicknessKind.SelectedIndex == 0)
                {
                    sick_kind = this.cboBigSicknessKind.Text;
                }
                else
                {
                    sick_kind = this.cboBigSicknessKind.SelectedValue.ToString();
                }

                //根据不同查询条件查询
                if (template_level == "请选择..." && template_name == "" && sys == "请选择...")
                {
                    msg = "";
                }
                else
                {
                    if (template_level != "请选择...")
                    {
                        //使用范围
                        if (template_level == "个人")
                        {
                            msg = " and tempplate_level='P' and CREATOR_ID='" + App.UserAccount.Account_id + "'"; //个人
                        }
                        if (template_level == "科室")
                        {
                            msg = " and tempplate_level='S' and c.SECTION_ID='" + section_id + "'"; //科室
                            Styleflag = "S";
                        }
                        if (template_level == "诊疗组")
                        {
                            msg = " and tempplate_level='G' and GROUP_ID='" + App.UserAccount.Group_id + "'"; //科室
                            Styleflag = "G";
                        }
                        if (template_level == "全院")
                        {
                            msg = " and tempplate_level='H'"; //全院
                        }
                        if (template_name != "")
                        {
                            msg += " and tname like '%" + template_name + "%'";
                        }
                        if (sys != "请选择...")
                        {
                            msg += " and s.sick_system='" + sys + "'";
                            if (sick_kind != "请选择...")
                            {
                                msg += " and t.sick_id='" + sick_kind + "'";
                            }
                        }
                    }
                    else if (template_level == "请选择...")
                    {
                        if (template_name != "")
                        {
                            msg += " and tname like '%" + template_name + "%'";
                        }
                        if (sys != "请选择...")
                        {
                            msg += " and s.sick_system='" + sys + "'";
                            if (sick_kind != "请选择...")
                            {
                                msg += " and t.sick_id='" + sick_kind + "'";
                            }
                        }
                    }
                }
                GetTemplateByCondition(msg, Styleflag);
            }
            catch
            { }
        }

        //根据条件，获得模板
        private void GetTemplateByCondition(string msg, string GStyle)
        {
            //inner join T_TEMPPLATE_GROUP d on t.tid=d.template_id
            DataSet ds = new DataSet();
            string Sql = "select distinct t.Tid,t.tname as 模板名称,t.create_time as 创建时间,t.TEMPPLATE_LEVEL as 模板级别 from t_tempplate t inner join t_sick_type s on t.sick_id=s.id ";
            if (GStyle == "G")
                Sql = "select distinct t.Tid,t.tname as 模板名称,t.create_time as 创建时间,t.TEMPPLATE_LEVEL as 模板级别 from t_tempplate t inner join t_sick_type s on t.sick_id=s.id inner join T_TEMPPLATE_GROUP c on t.tid=c.template_id";
            else if (GStyle == "S")
                Sql = "select distinct t.Tid,t.tname as 模板名称,t.create_time as 创建时间,t.TEMPPLATE_LEVEL as 模板级别 from t_tempplate t inner join t_sick_type s on t.sick_id=s.id inner join T_TEMPPLATE_SECTION c on t.tid=c.template_id ";

            if (msg == "")
            {
                ds.Clear();
                string tempSql = Sql + " where t.text_type='" + Kindtid + "' and t.tempplate_level='S' and t.SECTION_ID='" + section_id + "'";
                ds = App.GetDataSet(tempSql);
            }
            else
            {
                ds.Clear();
                string tempSql = Sql + " where text_type='" + Kindtid + "'" + msg;
                ds = App.GetDataSet(tempSql);
            }
            if (ds != null)
            {
                advTreeBigTemplate.Nodes.Clear();
                /*
                 * 类型主节点
                 */
                DevComponents.AdvTree.Node templateKindNode = new DevComponents.AdvTree.Node();
                templateKindNode.Text = TextData.Tables[0].Select("id=" + Kindtid + "")[0]["textname"].ToString();
                templateKindNode.Name = Kindtid + "_";
                templateKindNode.ImageIndex = 12;
                /*
                 *模板集合
                 */
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DevComponents.AdvTree.Node templateNode = new DevComponents.AdvTree.Node();
                    templateNode.Text = ds.Tables[0].Rows[i]["模板名称"].ToString();
                    templateNode.Name = ds.Tables[0].Rows[i]["Tid"].ToString();
                    templateKindNode.Nodes.Add(templateNode);
                    templateNode.ImageIndex = 13;
                }
                advTreeBigTemplate.Nodes.Add(templateKindNode);
                advTreeBigTemplate.ExpandAll();
            }
        }

        private void frmGetTemplate_Load(object sender, EventArgs e)
        {
            section_id = App.UserAccount.CurrentSelectRole.Section_Id;
            TextData = App.GetDataSet("select t.id,t.textname from t_text t");
            //大模板
            InitSystemList(ref cboBigSys);
            InitSickList(ref cboBigSicknessKind, cboBigSys.SelectedValue.ToString());
            cboBigUseRange.SelectedIndex = 2;
            btnSearch_Click(sender, e);          
        }

        /// <summary>
        /// 大模板查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {          
            BigCheck();
        }

        private void advTreeBigTemplate_AfterNodeSelect(object sender, DevComponents.AdvTree.AdvTreeNodeEventArgs e)
        {
            try
            {
                if (advTreeBigTemplate.SelectedNode.Nodes.Count == 0)
                {                    
                    string Content = App.wc.GetTemplateByid(advTreeBigTemplate.SelectedNode.Name);
                    uctext.MyDoc.ClearContent();
                    XmlDocument xdoc = new XmlDocument();
                    xdoc.LoadXml(Content);
                    uctext.MyDoc.FromXML(xdoc.DocumentElement);
                    uctext.MyDoc.ContentChanged();

                    ucDocOperater.SelectTemplate = Content;
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void advTreeBigTemplate_DoubleClick(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
